import logging
from datetime import datetime

import requests
import pandas as pd
from django.conf import settings

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from search_main.utlis import TimeUtils
from search_main.utlis import HttpClient
from search_main.utlis import token_51cto
from search_main.models import Hot51CTO
from search_main.serializers import Hot51CTOSerializer

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class Views51Cto(APIView, TimeUtils):
    PATH = "index/index/recommend"

    def __init__(self):
        super().__init__()
        self.http_client = HttpClient()
        self.time_utils = TimeUtils()
        self.timestamp = self.time_utils.get_timestamp()
        self.token = token_51cto.get_token()
        self.params = {
            'page': 1,
            'page_size': 50,
            'limit_time': 0,
            'name_en': '',
            'timestamp': self.timestamp,
            'token': self.token,
        }
        self.params["sign"] = token_51cto.sign(
            self.PATH,
            {k: v for k, v in self.params.items() if k not in ['sign', 'timestamp', 'token']},
            self.timestamp,
            self.token
        )

    def get(self, request):
        try:
            response = self.http_client.get_client(settings.API_51CTO_URL, self.params)
            raw_data = response['data']['data']['data']['list']
            # df = pd.DataFrame(raw_data)

            processed_data = []

            for item in raw_data:
                processed_data.append({
                    "source_id": item.get("source_id", ""),
                    "title": item["title"],
                    "cover": item.get("cover", ""),
                    "desc": item.get("abstract", ""),
                    "timestamp": (
                        self.time_utils.parse_time(item.get("pubdate"))
                        if item.get("pubdate")
                        else None
                    ),
                    "url": item["url"],
                    "mobile_url": item["url"]
                })

            result = {
                "name": "51cto",
                "title": "51CTO",
                "type": "推荐榜",
                "link": "https://www.51cto.com/",
                "total": len(processed_data),
                "data": processed_data,
                "update_time": self.time_utils.get_current_datetime(),
            }

            # =================
            print(f"最新热榜（共{result['total']}条）:")
            for idx, item in enumerate(processed_data[:10], 1):
                print(f"{idx}. [{item['timestamp']}] {item['title']}")
                print(f"   {item['desc']}")
                print(f"   详情链接：{item['url']}\n")
            # =================

            return Response(result, status=status.HTTP_200_OK)
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return Response(
                {"error": "服务暂不可用"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )
